<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::section})}">

<head>
    <title>用户列表 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>用户列表</h2>
            <a href="/user/add" class="btn btn-primary">
                <i class="fas fa-plus"></i> 添加用户
            </a>
        </div>

        <!-- 搜索表单 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">搜索条件</h5>
            </div>
            <div class="card-body">
                <form id="searchForm">
                    <div class="form-row">
                        <div class="form-group col-md-3">
                            <label for="username">用户名</label>
                            <input type="text" class="form-control" id="username" name="username">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="name">姓名</label>
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="phone">手机号码</label>
                            <input type="text" class="form-control" id="phone" name="phone">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="role">角色</label>
                            <select class="form-control" id="role" name="role">
                                <option value="">全部</option>
                                <option value="0">管理员</option>
                                <option value="1">普通用户</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-3">
                            <label for="gender">性别</label>
                            <select class="form-control" id="gender" name="gender">
                                <option value="">全部</option>
                                <option value="1">男</option>
                                <option value="2">女</option>
                            </select>
                        </div>
                        <div class="form-group col-md-3">
                            <label for="email">邮箱</label>
                            <input type="text" class="form-control" id="email" name="email">
                        </div>
                        <div class="form-group col-md-6 d-flex align-items-end">
                            <button type="button" id="searchBtn" class="btn btn-primary mr-2">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" id="resetBtn" class="btn btn-secondary">
                                <i class="fas fa-redo"></i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 用户列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">用户列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>手机号码</th>
                                <th>邮箱</th>
                                <th>角色</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="userList">
                            <!-- 用户数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页将通过AJAX加载 -->
                    </ul>
                </nav>
            </div>
        </div>

        <script>
            $(document).ready(function () {
                // 定义全局变量
                let currentPage = 1;
                let pageSize = 10;

                // 页面加载时获取数据
                loadData();

                // 搜索按钮点击事件
                $('#searchBtn').click(function () {
                    currentPage = 1;
                    loadData();
                });

                // 重置按钮点击事件
                $('#resetBtn').click(function () {
                    $('#searchForm')[0].reset();
                    currentPage = 1;
                    loadData();
                });

                // 加载数据函数
                function loadData() {
                    // 获取表单数据
                    const formData = {
                        username: $('#username').val(),
                        name: $('#name').val(),
                        phone: $('#phone').val(),
                        role: $('#role').val(),
                        gender: $('#gender').val(),
                        email: $('#email').val(),
                        pageNum: currentPage,
                        pageSize: pageSize
                    };

                    // 发送AJAX请求
                    $.ajax({
                        url: '/user/api/list',
                        type: 'GET',
                        data: formData,
                        success: function (res) {
                            if (res.code === 200) {
                                renderTable(res.data);
                                renderPagination(res.data);
                            } else {
                                alert('获取数据失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }

                // 渲染表格数据
                function renderTable(data) {
                    const list = data.list;
                    let html = '';

                    if (list && list.length > 0) {
                        for (let i = 0; i < list.length; i++) {
                            const user = list[i];
                            let genderText = user.gender === 1 ? '男' : (user.gender === 2 ? '女' : '未知');
                            let roleText = user.role === 0 ? '管理员' : '普通用户';
                            let roleBadge = user.role === 0 ? 'badge-danger' : 'badge-info';

                            html += `
                                <tr>
                                    <td>${user.id}</td>
                                    <td>${user.username}</td>
                                    <td>${user.name}</td>
                                    <td>${genderText}</td>
                                    <td>${user.phone || '-'}</td>
                                    <td>${user.email || '-'}</td>
                                    <td><span class="badge ${roleBadge}">${roleText}</span></td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="/user/detail/${user.id}" class="btn btn-info">
                                                <i class="fas fa-eye"></i> 详情
                                            </a>
                                            <a href="/user/edit/${user.id}" class="btn btn-primary">
                                                <i class="fas fa-edit"></i> 编辑
                                            </a>
                                            <button type="button" class="btn btn-danger" onclick="deleteUser(${user.id})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            `;
                        }
                    } else {
                        html = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                    }

                    $('#userList').html(html);
                }

                // 渲染分页
                function renderPagination(data) {
                    const total = data.total;
                    const totalPages = Math.ceil(total / pageSize);
                    let html = '';

                    // 上一页
                    html += `
                        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage - 1})">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                    `;

                    // 页码
                    for (let i = 1; i <= totalPages; i++) {
                        html += `
                            <li class="page-item ${currentPage === i ? 'active' : ''}">
                                <a class="page-link" href="javascript:void(0);" onclick="changePage(${i})">${i}</a>
                            </li>
                        `;
                    }

                    // 下一页
                    html += `
                        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage + 1})">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    `;

                    $('#pagination').html(html);
                }

                // 切换页码
                window.changePage = function (page) {
                    if (page < 1) page = 1;
                    currentPage = page;
                    loadData();
                };

                // 删除用户
                window.deleteUser = function (id) {
                    if (confirm('确定要删除这个用户吗？')) {
                        $.ajax({
                            url: '/user/api/delete/' + id,
                            type: 'DELETE',
                            success: function (res) {
                                if (res.code === 200) {
                                    alert('删除成功！');
                                    loadData();
                                } else {
                                    alert('删除失败：' + res.message);
                                }
                            },
                            error: function () {
                                alert('服务器错误，请稍后再试！');
                            }
                        });
                    }
                };
            });
        </script>
    </section>
</body>

</html>